//
//  YRJMineViewController.m
//  TravelAroundTheWorld
//
//  Created by dllo on 15/10/22.
//  Copyright (c) 2015年 yanrenjie. All rights reserved.
//

#import "YRJMineViewController.h"
#import "YRJTripHeader.h"
#import "YRJAboutSystemViewController.h"
#import "YRJSingleton.h"
#import <MessageUI/MessageUI.h>

//#import "AppDelegate.h"
//#define vBackBarButtonItemName  @"backArrow.png"    //导航条返回默认图片名

@interface YRJMineViewController ()<UITableViewDataSource, UITableViewDelegate, UMSocialUIDelegate, UIAlertViewDelegate, MFMailComposeViewControllerDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSArray *imageArr;
@property(nonatomic, retain)NSArray *nameArr;
@property(nonatomic, strong)NSData *fileData;
@property(nonatomic, retain)UIImageView *imageView;
@property(nonatomic, retain)NSFileManager *fileManager;
@property(nonatomic, retain)NSString *cachePath;
@property(nonatomic, assign)CGFloat cacheSize;
@end

@implementation YRJMineViewController
- (void)dealloc {
    [_tableView release];
    [_imageArr release];
    [_nameArr release];
    [_fileManager release];
    [_imageView release];
    [_fileData release];
    [_cachePath release];
    
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人中心";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    // 修改导航栏的背景颜色
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0 green:190 / 255.0 blue:200 / 255.0 alpha:1];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [_tableView release];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
/*
    self.imageArr = [NSArray arrayWithObjects:@"login.png", @"qingchu.png", @"shoucang.png", @"taiyang.png", @"guanyu.png", nil];
    self.nameArr = [NSArray arrayWithObjects:@"登录", @"清除缓存", @"我的收藏", @"夜间模式", @"关于系统", nil];
*/
    
    self.imageArr = [NSArray arrayWithObjects:@"qingchu.png", @"shoucang.png", @"taiyang.png",  @"help.png", @"guanyu.png", nil];
    self.nameArr = [NSArray arrayWithObjects:@"清除缓存", @"我的收藏", @"夜间模式", @"帮助和反馈", @"关于系统", nil];
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT / 4)];
    self.tableView.tableHeaderView = view;
    view.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:215 / 255.0  blue:193 / 255.0  alpha:0.7];
    [view release];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT / 4)];
    [view addSubview:imageView];
    imageView.image = [UIImage imageNamed:@"headImage.png"];
    [imageView release];
    
/*
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake((150.0 / 375) *SWIDTH, (30.0 / 667) * SHEIGHT, (75.0 / 375) * SWIDTH, (75.0 / 375) * SWIDTH)];
    [view addSubview:self.imageView];
    self.imageView.userInteractionEnabled = YES;
    self.imageView.image = [UIImage imageNamed:@"placeHold.png"];
    self.imageView.layer.borderWidth = 0.5;
    self.imageView.layer.cornerRadius = (75.0 / 375) * SWIDTH / 2;
    self.imageView.layer.masksToBounds = YES;
    [_imageView release];

    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    NSLog(@"imageFile->>%@",imageFilePath);
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];
    [self.imageView.layer setCornerRadius:CGRectGetHeight([self.imageView bounds]) / 2];
    self.imageView.layer.masksToBounds = YES;
    
    UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.imageView addGestureRecognizer:tap];
    tap.numberOfTapsRequired = 1;  // 需要点击的次数
    tap.numberOfTouchesRequired = 1;  // 需要几个手指进行触摸
    [tap release];
 */
}

#if 0
#pragma mark - 有关相册照相机的方法
- (void)tapAction:(UITapGestureRecognizer *)tap {
    //    /*注：使用，需要实现以下协议：UIImagePickerControllerDelegate,
    //     UINavigationControllerDelegate
    //     */
    //    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    //    //设置图片源(相簿)
    //    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    //    //设置代理
    //    picker.delegate = self;
    //    //设置可以编辑
    //    picker.allowsEditing = YES;
    //    //打开拾取器界面
    //    [self presentViewController:picker animated:YES completion:nil];
    UIActionSheet* actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"请选择文件来源"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"照相机",@"摄像机",@"本地相簿",@"本地视频",nil];
    [actionSheet showInView:self.view];
}

#pragma mark -
#pragma UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"buttonIndex = [%ld]",(long)buttonIndex);
    switch (buttonIndex) {
            //照相机
        case 0: {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
            //摄像机
        case 1: {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePicker.videoQuality = UIImagePickerControllerQualityTypeLow;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
            //本地相簿
        case 2: {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
            //本地视频
        case 3: {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}


#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeImage]) {
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    }
    else if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeMovie]) {
        NSString *videoPath = (NSString *)[[info objectForKey:UIImagePickerControllerMediaURL] path];
        self.fileData = [NSData dataWithContentsOfFile:videoPath];
    }
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)saveImage:(UIImage *)image {
    //    NSLog(@"保存头像！");
    //    [userPhotoButton setImage:image forState:UIControlStateNormal];
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    NSLog(@"imageFile->>%@",imageFilePath);
    success = [fileManager fileExistsAtPath:imageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    //    UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(80.0f, 80.0f)];//将图片尺寸改为80*80
    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(93, 93)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
    //    [userPhotoButton setImage:selfPhoto forState:UIControlStateNormal];
    self.imageView.image = selfPhoto;
}


// 改变图像的尺寸，方便上传服务器
- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size {
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


// 保持原来的长宽比，生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize {
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}
#endif


#pragma mark - tableView 的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (self.nameArr.count != 0) {
        cell.imageView.image = [UIImage imageNamed:self.imageArr[indexPath.row]];
        cell.textLabel.text = self.nameArr[indexPath.row];
        if (indexPath.row == 0) {
            self.fileManager = [NSFileManager defaultManager];
            self.cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            NSLog(@"%@", self.cachePath);
            self.cacheSize = [self folderSizeAtPath:self.cachePath];
            cell.textLabel.text = [NSString stringWithFormat:@"%@  (%.2f M)", self.nameArr[indexPath.row], self.cacheSize];
        }
    }
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (HEIGHT) / 7;
}


#pragma mark - tableView 的点击方法实现
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   if (indexPath.row == 0) {
        // 确定手机系统版本
        NSString *phoneVersion = [[UIDevice currentDevice] systemVersion];
        NSLog(@"手机系统版本: %@", phoneVersion);
        NSLog(@"%ld", (long)phoneVersion.integerValue);
        
        if (phoneVersion.integerValue >= 8) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要清除缓存吗?" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
                NSString *sandBoxPath = [sandBox lastObject];
                [self clearCache:sandBoxPath];
                
                [self.tableView reloadData];
                
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                [self.tableView reloadData];
            }];
            
            [alert addAction:action1];
            [alert addAction:action2];
            
            [self presentViewController:alert animated:YES completion:^{
                [self.tableView reloadData];
            }];
            
        } else {
            
            UIAlertView *alertVisionLow = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要清除缓存吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertVisionLow.delegate = self;
            [alertVisionLow show];
            [alertVisionLow release];
            
            [self.tableView reloadData];
        }
    } else if (indexPath.row == 1) {
//        if ([YRJSingleton shareSingleton].isLogin) {
            // 找到沙盒路径
            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            // 找到存放收藏的国家的路径
            NSString *docPath1 = [sandBoxPath stringByAppendingPathComponent:@"hot.plist"];
            // 反归档
            NSArray *countryArray = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath1];
            
            // 找到收藏城市的路径
            NSString *docPath2 = [sandBoxPath stringByAppendingPathComponent:@"hotCity.plist"];
            // 反归档
            NSArray *cityArray = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath2];
            NSMutableArray *tempCountryArray = [NSMutableArray array];
            NSMutableArray *tempCityArray = [NSMutableArray array];
            // 将数据传到下一个页面
            YRJShowMySavedViewController *showMySavedVC = [[YRJShowMySavedViewController alloc] init];
            [self.navigationController pushViewController:showMySavedVC animated:YES];
            
            for (YRJHotCountryModel *model in countryArray) {
                [tempCountryArray addObject:model];
            }
            
            for (YRJAllHotCityModel *model in cityArray) {
                [tempCityArray addObject:model];
            }
            
            showMySavedVC.savedCountryArray = tempCountryArray;
            showMySavedVC.savedCityArray = tempCityArray;
            [showMySavedVC release];
//        } else {
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//            [alert show];
//        }
    } else if (indexPath.row == 2) {
        if (self.view.window.alpha == 1) {
            self.view.window.alpha = 0.2;
            [YRJSingleton shareSingleton].isNight = NO;
            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *docPath = [sandBoxPath stringByAppendingPathComponent:@"isNight.txt"];
            NSString *isNightString = [NSString stringWithFormat:@"%hhd", [YRJSingleton shareSingleton].isNight];
            [isNightString writeToFile:docPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        } else {
            self.view.window.alpha = 1;
            [YRJSingleton shareSingleton].isNight = YES;
            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *docPath = [sandBoxPath stringByAppendingPathComponent:@"isNight.txt"];
            NSString *isNightString = [NSString stringWithFormat:@"%hhd", [YRJSingleton shareSingleton].isNight];
            [isNightString writeToFile:docPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
    } else if (indexPath.row == 3) {
        [self helpAndFeedbackAction];
    } else {
        YRJAboutSystemViewController *aboutSystemVC = [[YRJAboutSystemViewController alloc] init];
        self.tabBarController.tabBar.hidden = YES;
        [self.navigationController pushViewController:aboutSystemVC animated:YES];
        [aboutSystemVC release];
    }
}


#pragma mark - 清除缓存提示信息
- (void)clearCache:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
}


#if 0
#pragma mark - 第三方登录的方法实现
- (void)loginAction {
    if ([YRJSingleton shareSingleton].isLogin == NO) {
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
        snsPlatform.loginClickHandler(self, [UMSocialControllerService defaultControllerService], YES, ^(UMSocialResponseEntity *response) {
             //          获取微博用户名、uid、token等
            if (response.responseCode == UMSResponseCodeSuccess) {
                 UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToTencent];
//                [self.imageView sd_setImageWithURL:[NSURL URLWithString:snsAccount.iconURL]];
                [YRJSingleton shareSingleton].isLogin = YES;
            }
        });
    } else {
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:[YRJSingleton shareSingleton].pic]];
    }
}
#endif


#pragma mark - 计算缓存的大小
- (float )folderSizeAtPath:(NSString *)folderPath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.0 * 1024.0);
}


- (long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


#pragma mark - alertView 的协议方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *sandBoxPath = [sandBox lastObject];
        [self clearCache:sandBoxPath];
        [self.tableView reloadData];
    }
}


#pragma mark - push到下一页的时候隐藏Tabbar
- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
    animated = YES;
}


#pragma mark - 帮助反馈发送邮件的相关方法
- (void)helpAndFeedbackAction {
    Class mailClass = NSClassFromString(@"MFMailComposeViewController");
    if (mailClass) {
        if ([mailClass canSendMail]) {
            [self dispalyMailBox];
        } else {
            [self showMailBoxOneDevice];
        }
    }else {
        [self showMailBoxOneDevice];
    }
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    NSString *message;
    switch (result) {
        case MFMailComposeResultCancelled:
            message = @"取消发送";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultSaved:
            message = @"保存草稿";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultSent:
            message = @"已发送";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultFailed:
            message = @"发送失败";
            NSLog(@"%@", message);
            break;
            
        default:
            break;
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}


// 打开设备自带啊的邮件工具
- (void)showMailBoxOneDevice {
    NSString *mail = @"1282000376@qq.com";
    mail = [mail stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mail]];
    
    
}


- (void)dispalyMailBox {
    
    //创建邮箱的视图Vc
    MFMailComposeViewController *mailBox = [[MFMailComposeViewController alloc]init];
    // 接收人地址
    NSArray *arr = [NSArray arrayWithObjects:nil];
    [mailBox setToRecipients:arr];
    // 主题填写
    [mailBox setSubject:@"意见反馈"];
    
    NSString *messageBody = @"邮箱反馈";
    [mailBox  setMessageBody:messageBody isHTML:YES];
    //    //添加一个文件
    //    UIImage *image = [UIImage imageNamed:@"yindaoye0.png"];
    //    NSData *data = UIImagePNGRepresentation(image);
    //    [mailBox addAttachmentData:data mimeType:@"" fileName:@"beautiful.jpg"];
    // 代理人
    mailBox.mailComposeDelegate = self;
    
    //模态
    [self presentViewController:mailBox animated:YES completion:^{
        
        
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
